<template>
  <div>
    <!-- 面包屑 -->

    <el-header class="el-header2" height="35px">
      <el-breadcrumb
        style="margin-left: 10px"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色权限</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>

    <el-card>
      <el-button
        type="primary"
        class="button1"
        size="big"
        @click="dialog = !dialog"
        v-if="$store.getters.getUserInfoRoleid == '1'"
        >添加角色</el-button
      >
      <el-button
        style="margin-left: 20px"
        type="primary"
        class="button1"
        size="big"
        @click="showPowers"
        >权限列表</el-button
      >
      <!-- 主表 -->
      <div class="tableContainer">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="expand">
            <template v-slot="scope">
              {{ scope.row.id }}
              {{ scope.row.name }}
              {{ scope.row.des }}
              <br />
              {{ scope.row.power2[0][0][0].gpname }}
              <el-row
                :class="[i1 == 0 ? 'bdtop' : '', 'bdbottom', 'vcenter']"
                v-for="(item1, i1) in scope.row.power2"
                :key="item1[0][0][gpid]"
              >
                <!-- 一级权限 -->
                <el-col :span="5">
                  <el-tag>
                    {{ item1[0][0].gpname }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>

                <el-col :span="19">
                  <el-row
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                    v-for="(item2, i2) in item1"
                    :key="item2[0][pid]"
                  >
                    <!-- 2 -->
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        @close="removeRightById(scope.row, item2.id)"
                      >
                        {{ item2[0].pname }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 3 -->
                    <el-col :span="18">
                      <el-tag
                        closable
                        @close="removeRightById(scope.row, item3.sonid)"
                        type="warning"
                        v-for="item3 in item2"
                        :key="item3[sid]"
                      >
                        {{ item3.sname }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="Role Name"
            width="340"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="des"
            label="Description"
            width="520"
          >
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column align="center" prop="" label="操作" width="335">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="editrole(scope.row.id)"
                v-if="$store.getters.getUserInfoRoleid == '1'"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteRole(scope.row.id)"
                v-if="$store.getters.getUserInfoRoleid == '1'"
              >
                删除
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="showUpdatePower(scope.row)"
                v-if="$store.getters.getUserInfoRoleid == '1'"
              >
                分配权限
              </el-button>
              <el-button v-if="$store.getters.getUserInfoRoleid != 1">
                你没有权限噢
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div></el-card
    >

    <!-- 添加角色抽屉 -->
    <el-drawer
      title="我嵌套了 Form !"
      :visible.sync="dialog"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
      size="40%"
    >
      <el-form
        class="elform"
        :model="addRoleForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        width="100px"
      >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="addRoleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="des">
          <el-input v-model="addRoleForm.des"></el-input>
        </el-form-item>
      </el-form>
      <el-row type="flex" gutter="10" style="margin-top: '10px'">
        <el-col span="12" offset="5"
          ><el-button @click="dialog = !dialog">取 消</el-button></el-col
        >
        <el-col span="12">
          <el-button type="primary" @click="addRole">确定</el-button></el-col
        >
      </el-row>
    </el-drawer>

    <!-- 修改角色 -->
    <el-drawer
      title="我嵌套了 Form !"
      :visible.sync="dialog2"
      direction="ltr"
      custom-class="demo-drawer"
      ref="drawer"
      size="40%"
    >
      <el-form
        class="elform"
        :model="editRoleForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
        width="100px"
      >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="editRoleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="des">
          <el-input v-model="editRoleForm.des"></el-input>
        </el-form-item>
      </el-form>
      <el-row type="flex" gutter="10" style="margin-top: '10px'">
        <el-col span="12" offset="5"
          ><el-button @click="dialog2 = !dialog2">取 消</el-button></el-col
        >
        <el-col span="12">
          <el-button type="primary" @click="editRole">确定</el-button></el-col
        >
      </el-row>
    </el-drawer>

    <!--权限列表对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-card>
        <el-table :data="allpowers" border stripe>
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="name" label="权限名称"></el-table-column>
          <el-table-column prop="level" label="权限等级">
            <template v-slot="scope">
              <el-tag v-if="scope.row.level === '0'">一级标签</el-tag>
              <el-tag v-if="scope.row.level === '1'" type="success"
                >二级标签</el-tag
              >
              <el-tag v-if="scope.row.level === '2'" type="warning"
                >三级标签</el-tag
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showPowerUpdate"
      width="50%"
      @close="SetDialogVisableClose"
    >
      <!-- 分配权限对话框中间部分 -->
      <el-button
        size="small"
        type="primary"
        style="margin-bottom: 10px"
        @click="sendedit"
        >添加选中的权限</el-button
      >

      <!-- <el-table
        :data="allpowerss"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column label="id" prop="id"> </el-table-column>
        <el-table-column label="name" prop="name"> </el-table-column>
        <el-table-column label="level" prop="level"> </el-table-column>
      </el-table> -->
      <el-tree
        ref="treeref"
        :data="allpowerss"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all="true"
        :default-checked-keys="defKeys"
      ></el-tree>
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";

export default {
  data() {
    return {
      defKeys: [],
      treeProps: {
        // children: "children",
        label: "name",
      },
      // 分配权限选中的
      editPermission: {
        role_id: "",
        permission_id: [],
      },
      // 分配权限模块
      showPowerUpdate: false,
      // 权限列表对话框
      dialogVisible: false,
      // 权限列表数据
      allpowers: [],
      allpowerss: [],
      // 添加用户抽屉
      dialog: false,
      // 添加用户信息
      addRoleForm: {
        name: "",
        des: "",
      },
      // 修改用户抽屉
      dialog2: false,
      // 修改用户信息
      editRoleForm: {
        name: "",
        des: "",
        id: -1,
      },
      // 修改用户role
      editFormRules: {
        name: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      tableData: [
        {
          name: "loading",
          des: "loading",
        },
      ],
    };
  },
  async created() {
    this.getRoles();
    await this.getPowers();
    // 只显示二级
    const form = _.cloneDeep(this.allpowers);
    const form2 = form.filter((item) => {
      return item.level == 2;
    });
    console.log(355, form2);
    this.allpowerss = form2;
  },

  methods: {
    // 分配权限 提交更改
    async sendedit() {
      this.editPermission.permission_id = this.$refs.treeref.getCheckedKeys();
      this.editPermission.permission_id = this.editPermission.permission_id.join(
        ","
      );
      const { data } = await this.axios({
        url: "/role/updatepermission",
        method: "post",
        data: this.editPermission,
      });
      if (data.meta.status === 200) this.$message.success("更改权限成功");
      else this.$message.error("更改权限失败");
      this.getRoles();
      this.getPowers();
      this.showPowerUpdate = !this.showPowerUpdate;
    },
    // 分配权限选中时候改变
    // handleSelectionChange(val) {
    //   // console.log(val);
    //   this.editPermission.permission_id.push(val[val.length - 1].id);
    //   console.log(
    //     this.editPermission.permission_id,
    //     this.editPermission.role_id
    //   );
    // },

    // 关闭分配权限
    SetDialogVisableClose() {
      this.$refs.treeref.setCheckedKeys([]);
      this.defKeys = [];
      console.log(this.defKeys, "now");
    },

    // 删除分类
    async removeRightById(info, id) {
      // console.log(222, info);
      // console.log(333, id);
      if (this.$store.getters.getUserInfoRoleid == "1") {
        const permission = info.permission_id.split(",");
        const idd = permission.indexOf(id + "");
        permission.splice(idd, 1);
        const permissionlist = permission.join(",");
        console.log(permissionlist);
        const { data } = await this.axios({
          method: "post",
          url: `/role/updatepermission`,
          data: {
            role_id: info.id,
            permission_id: permissionlist,
          },
        });
        // console.log(data);
        if (data.meta.status === 200) {
          this.$message.success("修改成功");
          this.getRoles();
          this.getPowers();
        }
      } else {
        return this.$message.error("你没有权限噢");
      }
    },

    // 展示roles
    async getRoles() {
      const { data } = await this.axios({
        method: "get",
        url: `/role/roles`,
      });
      // console.log(data);
      const res = this.mysort(data);
      console.log(res);
      this.tableData = res;
    },

    // 分级处理
    mysort(data) {
      // let res = [];
      data.map((item) => {
        if (item.power) {
          const arr = [];
          item.power.forEach((list) => {
            arr.push(list[0]);
          });
          // 一级
          var sorted = this.groupBy(arr, function (item) {
            return [item.gpname];
          });
          // console.log(sorted);
          // 二级
          const brr = [];
          sorted.forEach((item) => {
            var sorted2 = this.groupBy(item, function (list) {
              return [list.pname];
            });
            brr.push(sorted2);
          });
          item.power2 = brr;
        }
      });
      return data;
    },

    // 通过groupyBy进行分级处理
    groupBy(array, f) {
      // debugger;
      var groups = {};
      array.forEach(function (o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
      });
      return Object.keys(groups).map(function (group) {
        return groups[group];
      });
    },

    // 添加角色-确定
    async addRole() {
      const { data } = await this.axios({
        method: "post",
        url: `/role/`,
        data: this.addRoleForm,
      });
      // console.log(data);
      if (data.meta.status && data.meta.status === 200)
        this.$message.success("成功添加");
      // console.log(this.$refs.drawer);
      this.getRoles();
      // this.$refs.drawer.closeDrawer();
      this.dialog = !this.dialog;
    },
    // 消失drawer
    cancel() {
      this.$refs.drawer.closeDrawer();
    },
    // 点删除
    async deleteRole(id) {
      // console.log(id);
      const { data } = await this.axios({
        method: "get",
        url: `/role/delete/${id}`,
      });
      if (data.status === 200) this.$message.success(data.msg);
      else this.$message.error("删除角色出现错误");
      this.getRoles();
    },
    // 点修改
    editrole(id) {
      this.dialog2 = !this.dialog2;
      this.editRoleForm.id = id;
    },

    // 点修改-确定
    async editRole() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入正确的信息！生气");

        console.log(this.editRoleForm.id);
        const id = this.editRoleForm.id;
        const { data } = await this.axios({
          method: "post",
          url: `/role/${id}`,
          data: this.editRoleForm,
        });
        if (data.status === 200) this.$message.success(data.msg);
        else this.$message.error("删除角色出现错误");
        this.$refs.drawer.closeDrawer();
        this.getRoles();
      });
    },

    // 权限列表 按钮
    async showPowers() {
      this.dialogVisible = !this.dialogVisible;
    },

    async getPowers() {
      const { data } = await this.axios({
        url: "/role/powers",
        method: "get",
      });
      this.allpowers = data;
    },

    // 分配权限-点击
    async showUpdatePower(info) {
      console.log(info);
      console.log(this.allpowerss);
      this.defKeys = info.permission_id.split(",");
      console.log(this.defKeys, "def");
      this.editPermission.role_id = info.id;
      // console.log(this.allpowers);
      // console.log(JSON.stringify(info.power2));
      this.showPowerUpdate = !this.showPowerUpdate;
    },
  },
};
</script>

<style lang="scss" scoped>
.button1 {
  margin-bottom: 25px !important;
}
.elform {
  margin-right: 50px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
.el-tag {
  margin: 7px;
}
</style>
